package com.bjpowernode.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JavaJwtUtil {
    public static final String secret = "0S/12dSd0=;2Sfdjkgh3OPYs";

    public static String createToken(String userJson) {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return JWT.create()
                .withHeader(header)
                .withClaim("user", userJson)
                .withClaim("phone", "13725121212")
                .withClaim("email", "13725121212@139.com")
                .withClaim("birthDay", new Date())
                .sign(Algorithm.HMAC256(secret));
    }

    public static Boolean verifyToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String parseToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            Claim user = decodedJWT.getClaim("user");
            System.out.println(user.asString());
            Claim phone = decodedJWT.getClaim("phone");
            System.out.println(phone.asString());
            Claim email = decodedJWT.getClaim("email");
            System.out.println(email.asString());
            Claim birthDay = decodedJWT.getClaim("birthDay");
            System.out.println(birthDay.asDate());
            return user.asString();
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
